<template>
  <div class="page-container">
    <el-form class="el-form-modify" ref="form" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="权益类型" prop="name">
        <el-input v-model="formData.name" placeholder="请输入权益类型" />
      </el-form-item>
      <el-form-item label="权益备注">
        <el-input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8}"
          placeholder="请输入权益备注"
          v-model="formData.remark">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save" size="small" :loading="saving">保存</el-button>
        <el-button @click="cancel" size="small">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {equityAdd, equityDetail, equityEdit} from '@/api/equityCategory'
import {rules} from '@/utils/validate'

export default {
  name: 'EquityForm',
  data() {
    return {
      formData: {
        id: 0,
        name: '',
        remark: ''
      },
      rules: {
        name: [rules.required, rules.text2_18],
        remark: [rules.textMax_128]
      },
      saving: false
    }
  },
  methods: {
    async requestDetail(id) {
      try {
        const {data} = await equityDetail(id)
        if (data) {
          this.formData.id = data.id;
          this.formData.name = data.name;
          this.formData.remark = data.remark;
        } else {
          this.cancel();
        }
      } catch(err) {
        this.cancel();
      }
    },
    save() {
      this.$refs.form.validate(async(valid) => {
        if (!valid) {
          return;
        }
        try {
          this.saving = true;
          const method = this.formData.id ? equityEdit : equityAdd
          await method(this.formData)
          this.saving = false;
          this.$message.success('保存成功!');
          this.$emit('refresh');
          this.cancel();
        } catch(err) {
          this.saving = false;
        }
      })
    },
    cancel() {
      this.$router.push({name: 'equityCategory'});
    }
  },
  created() {
    let {id} = this.$route.params;
    if (id) {
      this.requestDetail(id);
    }
  }
}
</script>

<style>

</style>